package com.example.spring_vue.utils;

import com.example.spring_vue.pojo.EmailProperties;
import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class MailUtil {

    /*
    * 发送邮件
    * @param emailProperties 发件人信息（发件人邮箱，发件人授权码）及邮件服务器信息（邮件服务器渔民，身份验证开关）
    * @param to 收件人邮箱
    * @param title 邮件标题
    * @param content 邮件正文
    */
    public static boolean sendMail(EmailProperties emailProperties, String to, String title, String content) {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", emailProperties.getHost());

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailProperties.getUser(), emailProperties.getCode());
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(emailProperties.getUser()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(title);
            message.setText(content);

            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}
